import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
// import { Loading } from 'element-ui'

// create an axios instance
const service = axios.create({
  // 基地址
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout 10s
})

// request interceptor
// 请求拦截器-统一注入token
service.interceptors.request.use(
  config => {
    // loading
    // Loading.service({ fullscreen: true })
    // do something before request is sent
    // 全局 请求头加token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器-解构数据-处理异常
service.interceptors.response.use(

  response => {
    // 先判断blob二进制流
    // axios默认包裹了data
    // 判断是不是Blob
    // 返回了Blob对象 默认json格式
    if (response.data instanceof Blob) return response.data
    // 解构
    const { message, data, code, success } = response.data
    console.log(message, success, code)
    // if the custom code is not 20000, it is judged as an error.
    // if (success && code === 10000) {
    if (success) {
      return data
    } else {
      Message({ type: 'error', message })
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  async error => {
    console.log('err' + error) // for debug
    // debugger打开控制台自动停止到这个位置
    // debugger
    if (error.response.status === 401) {
      // token 失效
      Message({ type: 'warning', message: error.response.data.message + ' token已过期' })
      await store.dispatch('user/logout') // 调用action 退出登录
      // 跳转登录页
      router.push('/')
      return Promise.reject(error)
    }
    // offset	距离窗口顶部的偏移量
    // Message({ type: 'error', message: error.message, offset: 100 })
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
